package com.lovo.project.service.impl;

import com.lovo.project.dao.GoodDAO;
import com.lovo.project.dao.OrderDAO;
import com.lovo.project.enums.OrderCodeEnum;
import com.lovo.project.exception.OurException;
import com.lovo.project.model.GoodDO;
import com.lovo.project.model.OrderDO;
import com.lovo.project.service.OrderService;
import com.lovo.project.util.MyBatisUtil;
import lombok.Data;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * @author pankez
 * @title 订单业务接口实现类
 * @data 2020/11/4 13:49
 */
@Data
public class OrderServiceImpl implements OrderService {


    @Override
    public List<OrderDO> findByItem(String type,String value) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        OrderDAO orderDao = sqlSession.getMapper(OrderDAO.class);
        try{
            List<OrderDO> list = orderDao.findByItem(type,value);

            if (list == null){
                throw new OurException(OrderCodeEnum.ORDER_FINDOUT_ENUM);
            }
            return list;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            sqlSession.close();
        }
        return null;
    }

    @Override
    public OrderDO findById(Integer id) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        OrderDAO orderDao = sqlSession.getMapper(OrderDAO.class);
        GoodDAO goodDao = sqlSession.getMapper(GoodDAO.class);
        try{
            OrderDO orderDO = orderDao.findById(id);

            List<GoodDO> goodList = goodDao.findGoodsByOrderId(id);
            orderDO.setGoods(goodList);

            if(orderDao == null){
                throw new OurException(OrderCodeEnum.ORDER_FINDOUT_ENUM);
            }
            return orderDO;
        }catch (Exception e){
            e.printStackTrace();
            
        }finally {
            sqlSession.close();
        }
        return null;
    }

    @Override
    public void updateOrder(OrderDO orderDO) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        OrderDAO orderDao = sqlSession.getMapper(OrderDAO.class);
        try{
            int order = orderDao.updateOrder(orderDO);
            if(order == 5404){
                throw new OurException(OrderCodeEnum.ORDER_UPDATE_ENUM);
            }
            sqlSession.commit();
        }catch (Exception e){
            sqlSession.rollback();
            e.printStackTrace();
        }finally {

            sqlSession.close();
        }
    }
}
